/**
* @author Roger Wu
* add the multiple selection function
*/

(function($) {
    var allSelectBox = [];
    var killAllBox = function(bid) {
        $.each(allSelectBox, function(i) {
            if (allSelectBox[i] != bid) {
                if (!$("#" + allSelectBox[i])[0]) {
                    $("#op_" + allSelectBox[i]).remove();
                    //allSelectBox.splice(i,1);
                } else {
                    $("#op_" + allSelectBox[i]).css({ height: "", width: "" }).hide();
                }
                $(document).unbind("click", killAllBox);
            }
        });
    };

    $.extend($.fn, {
        comboxSelect: function(options) {
            var op = $.extend({ selector: ">a" }, options);

            return this.each(function() {
                var box = $(this);
                var selector = $(op.selector, box);

                allSelectBox.push(box.attr("id"));
                $(op.selector, box).click(function() {
                    var options = $("#op_" + box.attr("id"));
                    if (options.is(":hidden")) {
                        if (options.height() > 300) {
                            options.css({ height: "300px", overflow: "scroll" });
                        }
                        var top = box.offset().top + box[0].offsetHeight;
                        if (top + options.height() > $(window).height() - 20) {
                            top = $(window).height() - 20 - options.height();
                        }
                        options.css({ top: top, left: box.offset().left }).show();
                        killAllBox(box.attr("id"));
                        $(document).click(killAllBox);
                    } else {
                        $(document).unbind("click", killAllBox);
                        killAllBox();
                    }
                    return false;
                });
                $("#op_" + box.attr("id")).find(">li").comboxOption(selector, box);
            });
        },
        comboxOption: function(selector, box) {
            return this.each(function() {
                $(">a", this).click(function(event) {
                    var $this = $(this);

                    if (box.hasClass("multiple")) {

                        var $input = $(":text", box);
                        if ($this.attr("value") == "") {
                            $this.parent().parent().find(".selected").removeClass("selected");
                            $this.addClass("selected");
                            $input.val("");
                            selector.text($this.text());
                        }
                        else {
                            $this.toggleClass("selected");

                            var text = "";
                            var value = "";
                            $this.parent().parent().find(".selected").each(function() {
                                var itemA = $(this);
                                if (itemA.attr("value") != "") {
                                    text += itemA.text() + ",";
                                    value += itemA.attr("value") + ","
                                }
                                else {
                                    itemA.removeClass("selected");
                                }
                            });
                            text = text.substring(0, text.length - 1);
                            value = value.substring(0, value.length - 1);

                            $input.val(value);

                            selector.text(text);
                            event.stopPropagation();
                        }
                    }
                    else {
                        $this.parent().parent().find(".selected").removeClass("selected");
                        $this.addClass("selected");

                        var $input = $("select", box);
                        if ($input.val() != $this.attr("value")) {

                            selector.text($this.text());
                            $input.val($this.attr("value")).trigger("refChange").trigger("change");
                        }
                    }
                });
            });
        },
        combox: function() {
            /* 清理下拉层 */
            var _selectBox = [];
            $.each(allSelectBox, function(i) {
                if ($("#" + allSelectBox[i])[0]) {
                    _selectBox.push(allSelectBox[i]);
                } else {
                    $("#op_" + allSelectBox[i]).remove();
                }
            });
            allSelectBox = _selectBox;

            return this.each(function(i) {
                var $this = $(this).removeClass("combox");
                var name = $this.attr("name");
                var value = $this.attr("value");
                if ($this.attr("svalue")) {
                    value = $this.attr("svalue");
                }

                var label = "";
                var ref = $this.attr("ref");
                var refUrl = $this.attr("refUrl") || "";
                var multiple = $this.attr("multiple");
                var readonly = $this.hasClass("readonly");

                var mockValue = ",,";
                if (value != "") {
                    mockValue = "," + value;
                    if (mockValue.substring(mockValue.length - 1) != ",") {
                        mockValue += ",";
                    }
                }

                var cid = $this.attr("id") || Math.round(Math.random() * 10000000);
                var options = '<ul class="comboxop" id="op_combox_' + cid + '">';
                $("option", $this).each(function() {
                    var option = $(this);
                    var select = "";

                    if (mockValue.indexOf("," + option[0].value + ",") >= 0) {
                        select = "selected";
                        label += option[0].text + ",";
                    }

                    options += "<li><a class=\"" + select + "\" href=\"#\" value=\"" + option[0].value + "\">" + option[0].text + "</a></li>";
                });
                options += "</ul>";

                if (multiple) {
                    if (label.length > 0) {
                        label = label.substring(0, label.length - 1);
                    }
                }
                else {
                    $this.val(value);
                    label = $("option[value=" + value + "]", $this).text();
                }


                var select = '<div class="combox ' + (readonly?"readonly":"") + '"><div id="combox_' + cid + '" class="select ' + (multiple ? "multiple" : "") + '"' + (ref ? ' ref="' + ref + '"' : '') + '>';
                select += '<a href="javascript:" class="' + $this.attr("class") + '" name="' + name + '" value="' + value + '">' + label + '</a></div></div>';


                $("body").append(options);
                $this.after(select);
                if (multiple) {
                    $("div.select", $this.next()).comboxSelect().append("<input type='text' name='" + name + "' value='" + value + "' style='display:none;'/>");
                    $this.remove();
                }
                else {
                    if (readonly) {
                        $("div.select", $this.next()).append($this);
                    }
                    else {
                        $("div.select", $this.next()).comboxSelect().append($this);
                    }
                }

                if (ref && refUrl) {

                    $this.unbind("refChange").bind("refChange", function(event) {
                        var $ref = $("#" + ref);
                        if ($ref.size() == 0) return false;
                        bee.PostData(refUrl.replace("{value}", escape($this.attr("value"))), {}, function(json) {
                            var html = '';
                            if (json) {
                                $.each(json, function(i) {
                                    var stringArray = json[i].split("$");
                                    if (stringArray.length > 1) {
                                        html += '<option value="' + stringArray[0] + '">' + stringArray[1] + '</option>';
                                    }
                                });
                            }

                            var $refCombox = $ref.parents("div.combox:first");
                            $ref.html(html).insertAfter($refCombox);
                            $refCombox.remove();
                            $ref.trigger("refChange").trigger("change").combox();
                        });

                    });
                }

            });
        }
    });
})(jQuery);
